import { Component, OnInit, ViewChild } from '@angular/core'
import * as ClassicEditor from '@ckeditor/ckeditor5-build-classic'
import { AppMessageDialogService } from 'src/app/service/app-message-dialog.service'
import AppApi from 'src/app/api'
import { MyMessageDetail } from 'src/app/common/message-dialog/message-dialog.component'
import { Publication } from '../../publication'
import { debounceTime } from 'rxjs/operators'
import { AppSnackBarService } from 'src/app/common/snack-bar/snack-bar.service'
@Component({
  selector: 'PubCreate',
  templateUrl: './pub-create.component.html',
  styleUrls: ['./pub-create.component.less']
})
export class PubCreateComponent implements OnInit {
  public Editor = ClassicEditor
  public pubType = 'info'
  private _publication = new Publication

  @ViewChild('theEditor')
  editor: any

  private _richTextContent = ''
  private _editorConfig = {
    alignment: {
      options: ['left', 'center', 'right']
    },
    toolbar:
      ['heading', '|', 'bulletedList', 'numberedList', 'alignment', '|', 'imageUpload', 'link', 'undo', 'redo']
  }

  constructor(
    private messageDialog: AppMessageDialogService,
    private snackBarService: AppSnackBarService
  ) { }

  ngOnInit(): void {
    this.publication.content = localStorage.getItem('richTextContent')
    this.publication.title = localStorage.getItem('richTextTitle')
    if (this.publication.content) {
      this.richTextContent = this.publication.content.toString()
      this.snackBarService.openLeftBottom('正文已恢复', 'ok')
    }
  }

  public onEditorReady(editor) {
    // console.log(Array.from(editor.ui.componentFactory.names()))
    // console.log(editor)
    // console.log(this.editor)
    this.editor.change
      .pipe(debounceTime(3000))
      .subscribe(
        changeEvent => {
          this.richTextContent = changeEvent.editor.getData()
          localStorage.setItem('richTextContent', this.richTextContent)
          localStorage.setItem('richTextTitle', this.publication.title.toString())
          this.snackBarService.openLeftBottom('正文已保存', 'ok')
        }
      )
  }

  /**
   * 校验当前富文本
   */
  private validatePublication() {
    const validInfo = { success: true, message: '' }
    if (!this.publication.type) {
      validInfo.success = false
      validInfo.message = '请选择公示类型'
    }
    if (!this.publication.title) {
      validInfo.success = false
      validInfo.message = '缺乏标题'
    }
    if (!this.publication.content || this.publication.content.length < 10) {
      validInfo.success = false
      validInfo.message = '正文内容不足'
    }
    if (this.publication.summary && this.publication.summary.length > 50) {
      validInfo.success = false
      validInfo.message = '超出摘要限制50字'
    }
    return validInfo
  }

  publish(): void {
    const messageDetail = new MyMessageDetail()
    messageDetail.confirmText = '发布'
    messageDetail.text = '确认发布'
    this.messageDialog.showAuthConfirmForm(
      AppApi.PubApi.create,
      this.publication,
      messageDetail)
      .subscribe(
        next => {
          if (next === false) {
            return // 对话框选择了取消
          }
          const validInfo = this.validatePublication()
          if (!validInfo.success) {
            this.messageDialog.showMessage('发布失败', validInfo.message)
          } else {
            next.subscribe(
              next2 => {
                if (next2.success) {
                  this.removeRichTextCache()
                  this.messageDialog.showMessage('发布完成', '')
                }
              },
              error => {
                this.messageDialog.showMessage(`出错了:${error.errTitle}`, error.errDetail)
              }
            )
          }
        }
      )
  }

  removeRichText() {
    this.publication = new Publication
    this.richTextContent = ''
  }
  removeRichTextCache() {
    localStorage.removeItem('richTextContent')
  }

  public get richTextContent() {
    return this._richTextContent
  }
  public set richTextContent(value) {
    this._richTextContent = value
  }
  public get editorConfig() {
    return this._editorConfig
  }
  public set editorConfig(value) {
    this._editorConfig = value
  }
  public get publication() {
    return this._publication
  }
  public set publication(value) {
    this._publication = value
  }
}
